import { app, ipcMain, BrowserWindow, dialog } from 'electron';
import fs from 'node:fs'
import fsPromises from 'node:fs/promises'
import path from 'node:path'
import { browserWindowManager } from './browserManager';
import { bridgeServer } from './bridgeServer'
import { playbackState, eventBus } from "@repo/executor"
// IPC处理程序

// 打开文件夹
ipcMain.handle('dialog:openDirectory', async () => {
  const { canceled, filePaths } = await dialog.showOpenDialog({
    properties: ['openDirectory']
  });
  return canceled ? null : filePaths[0];
});

// 获取根目录
ipcMain.handle('app:getHomeDir', () => {
  return path.join("C:\\gitee\\rpa-monorepo\\apps\\ide_playback\\src\\scripts")
  return app.getPath('home');
});

// 读取文件夹
ipcMain.handle('fs:readDirectory', async (event, dirPath) => {
  try {

    const items = await fsPromises.readdir(dirPath);

    const tree = await Promise.all(items.map(async (item) => {
      const itemPath = path.join(dirPath, item);
      const stats = await fsPromises.stat(itemPath)
      return {
        name: item,
        path: itemPath,
        type: stats.isDirectory() ? 'folder' : 'file',
        size: stats.size,
        modified: stats.mtime.toISOString()
      };
    }));
    return tree

  } catch (err: any) {
    throw new Error(`无法读取目录: ${err.message}`);
  }
});

// 读文件
ipcMain.handle('fs:readFile', async (event, dirPath) => {
  try {
    const dataString = await fsPromises.readFile(dirPath, { encoding: 'utf8' });
    return dataString
  } catch (err: any) {
    throw new Error(`无法读取文件: ${err.message}`);
  }
});

// 移动文件
ipcMain.handle('fs:moveFile', async (event, source, targetPath, targetName) => {
  try {
    const target = path.join(targetPath, targetName);
    await fsPromises.rename(source, target);
    return target;
  } catch (err: any) {
    throw new Error(`移动文件失败: ${err.message}`);
  }
});

// 创建文件夹
ipcMain.handle('fs:createFolder', async (event, basePath) => {
  try {
    const baseName = "新建文件夹";
    let newFolderPath = path.join(basePath, baseName);

    // 检查文件夹名是否已存在，如果存在则添加序号
    let counter = 1;
    while (fs.existsSync(newFolderPath)) {
      newFolderPath = path.join(basePath, `新建文件夹(${counter})`);
      counter++;
    }
    await fsPromises.mkdir(newFolderPath);
    return {
      folderPath: newFolderPath,
      folderName: path.basename(newFolderPath),
    };
  } catch (err: any) {
    throw new Error(`创建文件夹失败: ${err.message}`);
  }
});

// 创建文件
ipcMain.handle('fs:createFile', async (event, basPath) => {
  try {
    const baseName = "新建文件.json";
    let newFilePath = path.join(basPath, baseName);

    // 检查文件名是否已存在，如果存在则添加序号
    let counter = 1;
    while (fs.existsSync(newFilePath)) {
      newFilePath = path.join(basPath, `新建文件(${counter}).json`);
      counter++;
    }

    await fsPromises.writeFile(newFilePath, '');
    return {
      filePath: newFilePath,
      fileName: path.basename(newFilePath),
    };
  } catch (err: any) {
    throw new Error(`创建文件失败: ${err.message}`);
  }
});

// 重命名文件
ipcMain.handle('fs:renameFile', async (event, oldPath, newName) => {
  try {
    const newPath = path.join(path.dirname(oldPath), newName);

    await fsPromises.rename(oldPath, newPath);
    return newPath;
  } catch (err: any) {
    throw new Error(`重命名失败: ${err.message}`);
  }
});

// 删除文件
ipcMain.handle('fs:deleteFile', async (event, filePath) => {
  try {
    const stats = await fsPromises.stat(filePath);
    if (stats.isDirectory()) {
      await fsPromises.rmdir(filePath, { recursive: true });
    } else {
      await fsPromises.unlink(filePath);
    }
    return true;
  } catch (err: any) {
    throw new Error(`删除失败: ${err.message}`);
  }
});

// 复制文件
ipcMain.handle('fs:copyFile', async (event, source, targetPath, targetName) => {
  try {
    const target = path.join(targetPath, targetName);
    await fsPromises.copyFile(source, target);
    return target;
  } catch (err: any) {
    throw new Error(`复制文件失败: ${err.message}`);
  }
});

// task
ipcMain.handle('task:start', (event, taskName, config = {}) => {
  console.log(playbackState, 'playbackState')
  playbackState.start(taskName, config)
})
// 任务暂停
ipcMain.handle('task:pause', (event) => {
  playbackState.pause()
})
// 任务恢复
ipcMain.handle('task:resume', (event) => {
  playbackState.resume()
})
// 任务停止
ipcMain.handle('task:stop', (event) => {
  playbackState.stop()
})

//
/**
 * 创建新窗口
 * 窗口的数据是配置好的
 * 通过key创建
 */
ipcMain.on('window:create', (event, key) => {
  browserWindowManager.createBrowserWindow(key)
})
// 最小化窗口
ipcMain.on('window:minimize', (event) => {
  const webContents = event.sender;
  const win = BrowserWindow.fromWebContents(webContents);
  win?.minimize()
})
// 最大化窗口
ipcMain.on('window:maximize', (event) => {
  const webContents = event.sender;
  const win = BrowserWindow.fromWebContents(webContents);
  win?.maximize()
})
// 还原窗口
ipcMain.on('window:restore', (event) => {
  const webContents = event.sender;
  const win = BrowserWindow.fromWebContents(webContents);
  win?.unmaximize()
})
// 隐藏窗口
ipcMain.on('window:hide', (event) => {
  const webContents = event.sender;
  const win = BrowserWindow.fromWebContents(webContents);
  win?.hide()
})
// 关闭窗口
ipcMain.on('window:close', (event) => {
  const webContents = event.sender;
  const win = BrowserWindow.fromWebContents(webContents);
  win?.close()
})
// 打开调试工具
ipcMain.on('window:openDevtool', (event) => {
  const webContents = event.sender;
  webContents.openDevTools()
})

// 请求接口
ipcMain.handle('bridge:invoke', (event, args) => {
  bridgeServer.invokeMessage(args)
})

// 请求接口
ipcMain.on('bridge:send', (event, arg) => {
  bridgeServer.sendMessage(null, arg)
})

eventBus.on('task:started', (...args) => {
  const mainWindow = browserWindowManager.getBrowserWindow('MAIN')
  mainWindow.webContents.send('task:started', ...args)
})

eventBus.on('task:paused', () => {
  const mainWindow = browserWindowManager.getBrowserWindow('MAIN')
  mainWindow.webContents.send('task:paused')
})

eventBus.on('task:stoped', () => {
  const mainWindow = browserWindowManager.getBrowserWindow('MAIN')
  mainWindow.webContents.send('task:stoped')
})

eventBus.on('task:resumed', () => {
  const mainWindow = browserWindowManager.getBrowserWindow('MAIN')
  mainWindow.webContents.send('task:resumed')
})

eventBus.on('task:finished', (...args) => {
  const mainWindow = browserWindowManager.getBrowserWindow('MAIN')
  mainWindow.webContents.send('task:finished', ...args)
})

// 全部完成
eventBus.on('task:allFinished', () => {
  const mainWindow = browserWindowManager.getBrowserWindow('MAIN')
  mainWindow.webContents.send('task:allFinished')
})

// 某条命令完成
eventBus.on('task-command:done', (...args) => {
  const mainWindow = browserWindowManager.getBrowserWindow('MAIN')
  mainWindow.webContents.send('task-command:done', ...args)
})
